package com.test.netty.consumer;

import com.test.netty.handler.NettyClientHandler;
import com.test.netty.entity.Invocation;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

public class NettyClient {
    public void start(String hostName, Integer port, Invocation invocation) {

        Bootstrap bootstrap = new Bootstrap();
        EventLoopGroup work = new NioEventLoopGroup(1);

        bootstrap.group(work)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast("encoder", new ObjectEncoder());
                        pipeline.addLast("decoder", new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
                        pipeline.addLast("handler", new NettyClientHandler());
                    }
                });

        try {
            ChannelFuture channelFuture = bootstrap.connect(hostName, port).sync();
            Channel channel = channelFuture.channel();
            channel.writeAndFlush(invocation);

            /**
             * 等待连接端口关闭
             */
//            channel.closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            work.shutdownGracefully();
        }
    }

    public String send(String hostName, Integer port, Invocation invocation) {

        start(hostName, port, invocation);

        return "success";
    }
}
